package com.sa.token.utils;

import com.alibaba.fastjson.JSONObject;
import com.sa.token.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import com.ejlchina.okhttps.HTTP;

/**
 * @desc: 获取地址类
 * @projectName： sa-token-serve
 * @author： xhs
 * @date： 2021/12/29 15:36
 * @version: JDK 1.8
 */
@Slf4j
public class AddressUtils {

    /**
     * ip地址查询
     *
     * @param ip
     * @return
     */
    public static String getRealAddressByIP(String ip) {
        String address = Constants.UN_KNOWN;
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return Constants.INTRANET_IP;
        }
        try {
            HTTP http = HTTP.builder().build();
            String rspStr = http.sync(Constants.IP_URL)
                    .addPathPara("ip", ip)
                    .get()
                    .getBody()
                    .toString();
            if (!StringUtils.hasLength(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return Constants.UN_KNOWN;
            }
            JSONObject obj = JSONObject.parseObject(rspStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error("获取地理位置异常 {}", ip);
        }
        return address;
    }
}
